package com.google.code.gestion_de_conferences;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
 * This Activity creates all reservations 
 * 
 * @author Rayan Zahab <differentruna@gmail.com> 
 */
public class ReservationsListActivity extends Activity {

	private TextView tvDisplayDate;
	private TextView reservations ;//=(TextView) findViewById(R.id.reservations);
	private Button btnChangeDate, btn_Filter;
	AABDatabaseManager db;
	private int year;
	private int month;
	private int day;
	public String selectedUser="0";
	private String selectedRoom="0";
	private Date selectedDate;
	public int roomId = 1;
	MyData[] values ;
	MyData[] room_values;
	private final DateFormat ourFormat = new SimpleDateFormat("MM/dd/yyyy");

	static final int DATE_DIALOG_ID = 999;
	/**
	 * Initiates the activity
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reservations_list);
		db = new AABDatabaseManager(this);
		
		//Set date to current Day
		setCurrentDateOnView();
		//Add Buttons listeners
		addListenerOnButton();
		//Populate spinners values
		addItemsOnSpinners();
		
		//displayReservations();		
	}
	/** Populate values to Spinners:from , to , users
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */
	public void addItemsOnSpinners() {
		
		Spinner users_spinner = (Spinner) findViewById(R.id.users_spinner);
		Spinner rooms_spinner = (Spinner) findViewById(R.id.rooms_spinner);
		
		//Get all users from the db
		ArrayList<ArrayList<Object>> allUsersArrays = new ArrayList<ArrayList<Object>>();		    
	 	User user = new User();
	    allUsersArrays = db.getTablesRowsAsArrays (user);
	    
	    //array that will hold user data to be displayed
	    values = new MyData[allUsersArrays.size()];

	    String val="";

	    int user_count=1;
	    //Add all options first	    			  				    		
    	values = new MyData[allUsersArrays.size()];
		values[0] = new MyData("All","0");
		 
		if( allUsersArrays.size()>1)
		{			
		    //array that will hold user data to be displayed
			for (int position=0; position < allUsersArrays.size(); position++)
			{
				ArrayList<Object> row = allUsersArrays.get(position);				
				//check the is_admin value
				if(!(row.get(6)).equals("1") )
				{
					val = row.get(1).toString();
					values[user_count] = new MyData( val,row.get(0).toString()); 	 
					user_count=user_count+1;
				}								
	    	} 
		 }
		//Getting rooms 
		ArrayList<ArrayList<Object>> allRoomsArrays = new ArrayList<ArrayList<Object>>();
	    Room room = new Room();
	    String roomText="";
	    //Get all rooms in the db
	    allRoomsArrays = db.getTablesRowsAsArrays (room);
	    
	    //array that will hold user data to be displayed
	    room_values = new MyData[allRoomsArrays.size()+1];
	    //Add all options first	    			  				    		
	    room_values[0] = new MyData("All","0");
	    //check if we don't have any rooms
	    int room_count = 1;
		if(allRoomsArrays.size()>0)
		{
			for (int position=0; position < allRoomsArrays.size(); position++)
	    	{
	    		ArrayList<Object> row = allRoomsArrays.get(position);    		 			
	    		roomText =row.get(1).toString();
	    		//display full name - capacity
	    		room_values[room_count] = new MyData( roomText,row.get(0).toString());
	    		room_count = room_count + 1;
	    	} 
		}
		
    	    	
		ArrayAdapter<MyData> usersAdapter = new ArrayAdapter<MyData>(this,
												 android.R.layout.simple_spinner_item, values);
		usersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		users_spinner.setAdapter(usersAdapter);
    	
		ArrayAdapter<MyData> roomsAdapter = new ArrayAdapter<MyData>(this,
												 android.R.layout.simple_spinner_item, room_values);
		roomsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		rooms_spinner.setAdapter(roomsAdapter);
	    					
		rooms_spinner.setOnItemSelectedListener(
	            new AdapterView.OnItemSelectedListener() {
	                public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {
	                	if(room_values.length>0)
	                	{
		                   MyData roomData = room_values[position];
		                   selectedRoom= roomData.getValue() ;
		                   System.out.println("SelectedRoom: "+selectedRoom);
	                	}
	                }

	                public void onNothingSelected(AdapterView<?> parent) {
	                }
	            }
	        );
		users_spinner.setOnItemSelectedListener(
	            new AdapterView.OnItemSelectedListener() {
	                public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {
	                	if(values.length>0)
	                	{
		                   MyData userData = values[position];
		                   selectedUser= userData.getValue() ;
		                   System.out.println("SelectedUser: "+selectedUser);
	                	}
	                }

	                public void onNothingSelected(AdapterView<?> parent) {
	                }
	            }
	        );
		
		
	  }
	/**
	 * Set Date picker to current day
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */
	public void setCurrentDateOnView() {

		tvDisplayDate = (TextView) findViewById(R.id.tvDate);
		
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		// set current date into textview
		tvDisplayDate.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));

		try 
		{
			selectedDate = ourFormat.parse(tvDisplayDate.getText().toString());
		} 
		catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * Add listeners to buttons: changeDate, Reserve button
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */
	public void addListenerOnButton() {
		
		btnChangeDate = (Button) findViewById(R.id.btnChangeDate);		
		//SHow the date picket 
		btnChangeDate.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}

		});
		
		btn_Filter = (Button) findViewById(R.id.btnFilter);
		btn_Filter.setOnClickListener
    	(
    		new View.OnClickListener()
	    	{
				@Override 
				public void onClick(View v) {
					Intent is = new Intent(getApplicationContext(), ReservationsFilterListActivity.class);
					System.out.println("room: "+selectedRoom+"User: "+selectedUser+"date: "+selectedDate.toString());
					String[] res_ids = displayReservations(selectedRoom,selectedUser,selectedDate);

			        is.putExtra("selected", res_ids);
			        startActivity(is);
			    			    	
				}
			}
    	);				

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,day);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;
			// set selected date into textview
			tvDisplayDate.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));
			try {
				selectedDate = ourFormat.parse(tvDisplayDate.getText().toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	/**
	 * Prints all reservations of a selected date for the selected room
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */	
	private String[] displayReservations(String selectedRoom,String selectedUser,Date selectedDate)
	{
		ArrayList<String> res_ids = new ArrayList<String>();
    	
    	        
    	ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
    	dataArrays=db.getRowAsArrayByPosition(1,"Reservation",selectedDate.toString());
    	System.out.println("disp: "+dataArrays.size());
    	if(dataArrays.size()<1)
    	{
    		//reservations.setText("No reservations!");
    		System.out.println("no reser");
    	}
    	else
    	{
	    	for (int position=0; position < dataArrays.size(); position++)
	    	{	    		
	    		ArrayList<Object> row = dataArrays.get(position);
	    		 
	    		String room=row.get(4).toString();
	    		String user=row.get(5).toString();
	    		
    			if( (!selectedRoom.equals("0")) && (selectedUser.equals("0")))
	    		{	
		    		if(room.equals(selectedRoom))
		    		{
		    			res_ids.add(row.get(0).toString());
		    		}
	    		}
	    		else if( (selectedRoom.equals("0")) && (!selectedUser.equals("0")))
	    		{	
		    		if(user.equals(selectedUser))
		    		{
		    			res_ids.add(row.get(0).toString());
		    		}
	    		}
	    		else if( (selectedRoom.equals("0")) && (selectedUser.equals("0")))
	    		{
	    			res_ids.add(row.get(0).toString());
	    		}else if( (selectedRoom.equals("0")) && (selectedUser.equals("0")))
	    		{
	    			if( (user.equals(selectedUser)) && (room.equals(selectedRoom)) )
		    		{
		    			res_ids.add(row.get(0).toString());
		    		}
	    		}
	    			
	    	} 
    	}		
		String[] return_ids = new String[res_ids.size()];
		for(int i=0;i<res_ids.size();i++)
		{
			return_ids[i]=res_ids.get(i);
		}
  
		return return_ids;
	}
	
	
	class MyData {
        public MyData( String spinnerText, String value ) {
            this.spinnerText = spinnerText;
            this.value = value;
        }

        public String getSpinnerText() {
            return spinnerText;
        }

        public String getValue() {
            return value;
        }

        public String toString() {
            return spinnerText;
        }

        String spinnerText;
        String value;
    }
	/**
	   * This function create the menu in the user info activity
	   * @author Moustafa Chouraiki <mrsafu@gmail.com>
	   * @param menu
	   */
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.menu, menu);              
       return true;
   }
   
   /**
     * This function handles clicking any of the menu's items
     * @author Rayan Zahab <differentruna@gmail.com> 
     * @author Hyame Alameddine <hyame.alameddine@gmail.com>
     * @param menu
     */
   @Override
   public boolean onOptionsItemSelected(MenuItem item) 
    {       
        Intent i;
        
        switch (item.getItemId()) 
        {
         
        case R.id.users:     
              i = new Intent(getApplicationContext(), UsersListActivity.class);
              startActivity(i);
              break;
        case R.id.reservations:     
              i = new Intent(getApplicationContext(), ReservationsListActivity.class);
              startActivity(i);
              break;
        case R.id.conferences:     
              i = new Intent(getApplicationContext(), RoomsListActivity.class);
              startActivity(i);
              break;
        case R.id.edit_profile:                         
              i = new Intent(getApplicationContext(), RegisterActivity.class);
              i.putExtra("editAdmin", 1);
              startActivity(i);
              break;
        case R.id.logout: 
              i = new Intent(getApplicationContext(), LoginActivity.class);
              startActivity(i);
              break;
        case R.id.help:     
              AlertDialog alertDialog = new AlertDialog.Builder(this).create();
              alertDialog.setTitle("Help!");
              alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
              alertDialog.setIcon(R.drawable.icon);
              alertDialog.show();
              break;
        case R.id.developers: 
              Toast.makeText(this, "Rayan,Hyame,Mostafa!", Toast.LENGTH_LONG).show();
              break;
          
      }
      return true;
  }  

}